﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Personal_Cloud_Disk_PC_Client
{
    public class TaskScheduler
    {
        private Queue<CloudTask> taskQueue = new Queue<CloudTask>();
        Thread shcedulerThread;
        volatile bool schedulerOn;

        public TaskScheduler()
        {
            shcedulerThread = new Thread(new ThreadStart(this.handleTask));
        }

        public void start()
        {
            schedulerOn = true;
            Logger.write("Task scheduler starting, current state: " + shcedulerThread.ThreadState);
            if (shcedulerThread.ThreadState == ThreadState.Stopped || shcedulerThread.ThreadState == ThreadState.Unstarted) {
                shcedulerThread.Start();
            }
        }

        public void stop()
        {
            schedulerOn = false;

        }

        public void add(CloudTask cloudTask)
        {
            lock (taskQueue) {
                taskQueue.Enqueue(cloudTask);
            }
            Logger.write("Task added: " + cloudTask.ToString());
        }

        public void handleTask()
        {
            Logger.write("handleTask thread started!");
            while (schedulerOn) {
                lock (taskQueue) {
                    if (taskQueue.Count == 0) {
                        Thread.Sleep(100);
                        continue;
                    }
                    CloudTask cloudTask = taskQueue.Dequeue();
                    cloudTask.doWork();
                    Logger.write("Task handled: " + cloudTask.ToString());
                }
                Thread.Sleep(100);
            }
            Logger.write("handleTask thread ended!");
        }

    }

}
